package top.eggcode.gateway.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import top.eggcode.common.lang.StringUtil;
import top.eggcode.common.mvc.ResultStatus;
import top.eggcode.component.session.Session;
import top.eggcode.component.session.SessionHelper;
import top.eggcode.gateway.model.IgnoreWhiteProperties;
import top.eggcode.gateway.util.ServletUtils;

/**
 * 网关鉴权
 *
 * @author ruoyi
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered {
    private static final Logger log = LoggerFactory.getLogger(AuthFilter.class);

    // 排除过滤的 uri 地址，nacos自行添加
    @Autowired
    private IgnoreWhiteProperties ignoreWhite;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpRequest.Builder mutate = request.mutate();

        /* 跳过不需要验证的路径 */
        String url = request.getURI().getPath();
        if (StringUtil.matches(url, ignoreWhite.getWhites())) {
            return chain.filter(exchange);
        }

        String sessionId = getToken(request);
        if (StringUtil.isEmpty(sessionId)) {
            return unauthorizedResponse(exchange, "未携带 session-id");
        }

        /* 刷新 session 时间 */
        Session session = SessionHelper.getSession(sessionId);
        try {
            session.touch();
        } catch (Throwable var6) {
            log.error("session.touch() method invocation has failed.  Unable to update the corresponding session's last access time based on the incoming request.", var6);
        }



        /* 检查登录状态 */
        boolean isLogin = SessionHelper.isAuthenticated(sessionId);
        if (!isLogin) {
            return unauthorizedResponse(exchange, "身份认证已过期");
        }

        /* 清楚内部访问标记 */
        removeHeader(mutate, "source");

        return chain.filter(exchange.mutate().request(mutate.build()).build());
    }

    private void addHeader(ServerHttpRequest.Builder mutate, String name, Object value) {
        if (value == null) {
            return;
        }
        String valueStr = value.toString();
        String valueEncode = ServletUtils.urlEncode(valueStr);
        mutate.header(name, valueEncode);
    }

    private void removeHeader(ServerHttpRequest.Builder mutate, String name) {
        mutate.headers(httpHeaders -> httpHeaders.remove(name)).build();
    }

    private Mono<Void> unauthorizedResponse(ServerWebExchange exchange, String msg) {
        log.error("[鉴权异常处理]请求路径:{}", exchange.getRequest().getPath());
        return ServletUtils.webFluxResponseWriter(exchange.getResponse(), msg, ResultStatus.UNAUTHORIZED.getCode());
    }

    /**
     * 获取请求token
     */
    private String getToken(ServerHttpRequest request) {
        String token = request.getHeaders().getFirst("session-id");
        return token;
    }

    @Override
    public int getOrder() {
        return -200;
    }
}